//
//  MultiplexerProxyBehaviour.m
//  StoryboardObject
//
//  Created by CaryaLiu on 2021/4/12.
//

#import "MultiplexerProxyBehaviour.h"

@implementation MultiplexerProxyBehaviour

- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
    NSMethodSignature *sig = [super methodSignatureForSelector:aSelector];
    if (!sig) {
        for (NSValue *nonRetain in _targets) {
            id obj = [nonRetain nonretainedObjectValue];
            if ((sig = [obj methodSignatureForSelector:aSelector])) {
                break;
            }
        }
    }
    return sig;
}

- (BOOL)respondsToSelector:(SEL)aSelector {
    BOOL base = [super respondsToSelector:aSelector];
    if (base) {
        return base;
    }
    BOOL responds = NO;
    for (NSValue *nonRetain in _targets) {
        id obj = [nonRetain nonretainedObjectValue];
        if ([obj respondsToSelector:aSelector]) {
            responds = YES;
            break;
        }
    }
    return responds;
}

- (void)forwardInvocation:(NSInvocation *)anInvocation {
    for (NSValue *nonRetain in _targets) {
        id obj = [nonRetain nonretainedObjectValue];
        if ([obj respondsToSelector:anInvocation.selector]) {
            [anInvocation invokeWithTarget:obj];
        }
    }
}

#pragma mark - getter & setter

- (NSArray *)targets {
    NSMutableArray *mutableTargets = @[].mutableCopy;
    for (NSValue *targetValue in _targets) {
        [mutableTargets addObject:[targetValue nonretainedObjectValue]];
    }
    return  mutableTargets.copy;
}

- (void)setTargets:(NSArray *)targets {
    NSMutableArray *mutableTartes = @[].mutableCopy;
    for (id target in targets) {
        [mutableTartes addObject:[NSValue valueWithNonretainedObject:target]];
    }
    _targets = mutableTartes.copy;
}

@synthesize targets = _targets;
@end
